package com.example.login.service;

import com.example.login.dao.UserRepository;
import com.example.login.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

@Service
public class UserService {
    @Autowired
    UserRepository userRepository;

    //登录
    public User checkLogin(User user, Model model) {
        User findUser = userRepository.findByUsername(user.getUsername());
        //判断用户是否存在
        if (findUser == null) {
            model.addAttribute("error", "用户名不存在");
            return null;
        } else {
            if (findUser.getPassword().equals(user.getPassword())) {
                return findUser;
            } else {
                model.addAttribute("error", "用户名和密码不匹配");
                return null;
            }
        }
    }

    //注册
    public User addUser(User user, Model model) {
        try {
            User registeredUser = userRepository.findByUsername(user.getUsername());
            //判断当前用户是否已经存在
            if (registeredUser == null) {
                registeredUser = userRepository.save(user);
                return registeredUser;
            } else
                model.addAttribute("error", "该用户已存在！");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", e.getMessage());
        }
        return null;
    }

}
